<?php

/* * 
 * 分类模型
 */
namespace Admin\Model;
use Common\Model\CommonModel;



class CateModel extends CommonModel {

    //array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
    protected $_validate = array(
        array('name', 'require', '栏目名称不能为空！', 1, 'regex', 3),
 
    	array('model', 'require', '模型不能为空！', 1, 'regex', 3),    
    array('catdir', '', '目录已经存在！', 2 ,'unique', CommonModel:: MODEL_BOTH   ),       
        //验证栏目类型
        array('type', array(1, 2,3,4), '栏目类型错误！', 1, 'in', 3)
    );

  
    

    /**
     * 添加栏目
     * @param type $data 页面提交数据
     * @return boolean]
     */
    public function addCategory($post) {
    	
    	
    	if ($this->create ( $post )) {
    		if ($this->add () !== false) {
    				
    			$this->success ( "添加成功！" );
    		} else {
    			$this->error ( "添加失败！" );
    		}
    	} else {
    		$this->error ( $this->getError () );
    	}
    	
    	
    }

    /**
     * 编辑栏目
     * @param type $post 页面提交过来的数据
     * @return boolean
     */
    public function editCategory($post) {
    	


    	if ($this->create ( $post )) {
    		if ($this->save () !== false) {
    			$this->success ( "更新成功！", U ( "index" ) );
    		} else {
    			$this->error ( "更新失败！" );
    		}
    	} else {
    		$this->error ( $this->getError () );
    	}
    	
    
    }

    /**
     * 删除栏目，如果有子栏目，会删除对应的子目录
     * @param type $catid 可以是数组，可以是栏目id
     * @return boolean
     */
    public function deleteCatid($catid) {
        if (!$catid) {
            return false;
        }
        $where = array();
        //取得子栏目
        if (is_array($catid)) {
            $where['catid'] = array("IN", $catid);
            $catList = $this->where($where)->select();
            foreach ($catList as $cat) {
                //是否存在子栏目
                if ($cat['child'] && $cat['type'] == 0) {
                    $arrchildid = explode(",", $cat['arrchildid']);
                    unset($arrchildid[0]);
                    $catid = array_merge($catid, $arrchildid);
                }
            }
            $where['catid'] = array("IN", $catid);
        } else {
            $where['catid'] = $catid;
            $catInfo = $this->where($where)->find();
            //是否存在子栏目
            if ($catInfo['child'] && $catInfo['type'] == 0) {
                $arrchildid = explode(",", $catInfo['arrchildid']);
                unset($arrchildid[0]);
                $catid = array_merge($arrchildid, array($catid));
                $where['catid'] = array("IN", $catid);
            }
        }
        //检查是否存在数据，存在数据不执行删除
        if (is_array($catid)) {
            $modeid = array();
            foreach ($catid as $cid) {
                $catinfo = getCategory($cid);
                if ($catinfo['modelid'] && $catinfo['type'] == 0) {
                    $modeid[$catinfo['modelid']] = $catinfo['modelid'];
                }
            }
            foreach ($modeid as $mid) {
                $tbname = ucwords(getModel($mid, 'tablename'));
                if (!$tbname) {
                    return false;
                }
                if ($tbname && M($tbname)->where(array("catid" => array("IN", $catid)))->count()) {
                    return false;
                }
            }
        } else {
            $catinfo = getCategory($catid);
            $tbname = ucwords(getModel($catInfo['modelid'], 'tablename'));
            if (!$tbname && $catinfo['type'] == 0) {
                return false;
            }
            if ($tbname && $catinfo['type'] == 0 && M($tbname)->where(array("catid" => $catid))->count()) {
                return false;
            }
        }
        $status = $this->where($where)->delete();
        //更新缓存
        S('Category', NULL);
        if (false !== $status) {
            $this->extendFieldDel($where);
            //删除对应栏目的权限列表
            M("Category_priv")->where($where)->delete();
            if (is_array($catid)) {
                //删除附件
                foreach ($catid as $cid) {
                    service("Attachment")->api_delete('catid-' . $cid);
                }
            } else {
                service("Attachment")->api_delete('catid-' . $catid);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取子栏目ID列表
     * @staticvar type $categorys 静态变量 栏目数据
     * @param type $catid 栏目id
     * @return string 返回栏目子列表，以逗号隔开
     */
    public function getArrchildid($catid) {
 
          $categorys = F('Cates');
       //   print_r($categorys);
   
        $arrchildid = $catid;
        if (is_array($categorys)) {
            foreach ($categorys as $id => $cat) {
                if ($cat['parentid'] && $id != $catid && $cat['parentid'] == $catid) {
                    $arrchildid .= ',' . $this->getArrchildid($id);
                }
            }
        }
        return $arrchildid;
    }

    /**
     * 获取父栏目ID列表
     * @param integer $catid              栏目ID
     * @param array $arrparentid          父目录ID
     * @param integer $n                  查找的层次
     */
    public function getArrparentid($catid, $arrparentid = '', $n = 1) {
       
            $categorys = F('Cates');
     
      
        //获取当前栏目的上级栏目ID
        $parentid =$categorys[$catid]['parentid'];  //48
        //所有父ID
       
        
        if ($parentid) {
            $arrparentid = $this->getArrparentid($parentid, $arrparentid, ++$n);
            $arrparentid .= ',' . $catid ;
            
            return $arrparentid;
        } 
        else{
        	
        	return $catid;
        }
        
        
    }
    
    public function data_cache(){
    	
    	$data=$this->order('redirt ASC')->select();
    	$route=array();
    	foreach ($data as $k =>$v){
    		
    		$t=array(
    			"id"=>$v[id],
    			"arrchildid"=>$this->getArrchildid($v[id]),
    			"arrparentid"=>$this->getArrparentid($v[id]),
    			"letter"=>pinyin($v[name])
    			  				
    		);
    		
    		if($v[model]!="Link"){
    			//echo $v[model];
    			$t[url]=D($v[model])->get_cate_url($v);
    			$s=D($v[model])->get_route($v);
    			if($s){
    				$route=array_merge($s,$route);
    			
    			}
    			
    			//echo $t[url];
    		}
    		if($v[redirt]){
    			$t['url']=$this->where(array("parentid"=>$v['id']))->order("listorder DESC,id DESC")->getField("url");
    			 
    			 
    		}
    		$ts=$this->where(array("parentid"=>$v['id']))->count();
    		$t['child']=$ts?1:0;
    	
    		$this->save($t);
    		
    	}
    	
//     	$data=$this->where(array("redirt"=>1))->select();
    	
//     		foreach ($data as $k =>$v){
//     			$z=$this->where(array("parentid"=>$v[id]))->order("listorder ASC,id DESC")->find();
//     			$ts[url]=$z[url];
//     			$ts['id']=$v[id];
//     			$this->save($ts);
    			
//     		}
    	
    	F("Cate_route",$route);
    	
    	
    }



    //刷新栏目索引缓存
    public function category_cache() {
        $data = $this->field('content',true)->order("listorder DESC,id DESC")->where(array("status"=>"1"))->select();
    
        foreach ($data as $r) {
            $result[$r['id']] =$r;
            
            if($r['child']==1){
            	 
            $cls[]=$r['id'];	 
            	 
            }
            
            
        }
        F("Cates", $result);
        
        
      
         
        import("Tree");
        $tree = new \Tree();
        $tree->init($result);
         
        foreach($cls as $k=>$v){
        	
        	$trees= $tree->get_tree_array($v);
        	
        	F("Cates_tree_".$v, $trees);
        	
        }
        
        $tree= $tree->get_tree_array(0);
        
        F("Cates_tree", $tree);
    
    }
    
    public function get_admin_tree($value){
    	
    	import("Tree");
    	$tree = new \Tree();
    
    	$result = $this->order(array("listorder" => "DESC"))->select();
    	
    	
    	foreach ($result as $r) {
    	
    		$r['selected'] = $r['id'] == $value ? 'selected' : '';
    		$r['disable'] = ($r['type'] == 2|$r['type'] == 4) ? 'disabled' : '';
    	
    		$array[] = $r;
    	}
    	
    	$str = "<option value='\$id' \$selected \$disable>\$spacer \$name</option>";
    	$tree->init($array);
    	$select_categorys = $tree->get_tree(0, $str);
    	
    	return $select_categorys;
    	
    	
    	
    }
    public function get_article_tree($value,$model="Article"){
    	 
    	import("Tree");
    	$tree = new \Tree();
    
    	$result = $this->order(array("listorder" => "DESC"))->select();
    	 
    	 
    	foreach ($result as $r) {
    		 
    		$r['selected'] = $r['id'] == $value ? 'selected' : '';
    		$r['disable'] = $r['type'] != 2 ? 'disabled' : '';
    		 
    		$array[] = $r;
    	}
    	 
    	$str = "<option value='\$id' \$selected \$disable>\$spacer \$name</option>";
    	$tree->init($array);
    	$select_categorys = $tree->get_tree(0, $str);
    	 
    	return $select_categorys;
    	 
    	 
    	 
    }
    public function _after_write() {

    }
    public function _after_update() {

    }

    public function _after_insert() {

    }
    //删除操作时删除缓存
    public function _after_delete() {

    }



	}

?>